C++에서는 커뮤니케이션은 흐름이며, 정적 저장 이벤트가 아닙니다. iostream 라이브러리는 다형성 계층 구조 특수화된 클래스들인 ifstream (파일)과 istringstream (메모리)는 istream에서 상속됩니다. 이를 통해 스트림 상속이 가능합니다. 기본 스트림용으로 설계된 함수는 어떤 소스로부터든 데이터를 투명하게 처리할 수 있습니다.
복사 불가 제약 조건
스트림은 하드웨어에 대한 고유하고 상태 기반의 연결을 나타냅니다. 동일한 파일 포인터나 콘솔 버퍼를 여러 개체가 경쟁하지 않도록 하기 위해, 입출력 객체는 복사하거나 할당할 수 없습니다. 다음 코드를 시도하면 ofstream out1, out2; out1 = out2; 컴파일러 오류가 발생합니다. 따라서 입출력 객체는 비-상수 참조로 전달되어야 합니다.
순차적 브리지
스트림은 인터페이스를 제공하지만, 순차 컨테이너 (vector, list)는 메모리를 제공합니다. 스트리밍된 데이터는 일반적으로 이러한 컨테이너에 구조화되며, 속도를 위해 vector 또는 유연한 삽입을 위해 list 를 선택합니다.
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What causes the termination of
while (cin >> i)?The stream reaching a value of 0.
Encountering end-of-file (EOF) or an invalid input type.
The buffer becoming full.
A semicolon in the input stream.
✅ Correct!
Correct. The expression evaluates to the stream itself, which in a boolean context returns false if the stream's failbit or eofbit is set.❌ Incorrect
The while loop terminates when the stream state becomes invalid, such as entering a character when an integer was expected.QUESTION 2
Identify the error:
ofstream out1, out2; out1 = out2;Logic error: Files cannot have the same name.
Syntax error: Stream assignment is prohibited.
Runtime error: Buffer overflow.
No error; this is standard C++ usage.
✅ Correct!
Stream objects are non-copyable and non-assignable to prevent ambiguous hardware management.❌ Incorrect
C++ deletes the copy constructor and assignment operator for IO classes.QUESTION 3
How should an
istream be passed to a function that reads from it?By value (e.g., void func(istream is))
By const reference (e.g., void func(const istream &is))
By non-const reference (e.g., void func(istream &is))
As a pointer to a const object.
✅ Correct!
Reading from a stream changes its internal state (e.g., position pointers), so it must be a non-const reference.❌ Incorrect
Since streams are non-copyable, 'by value' is impossible. Since reading modifies the stream, 'const reference' is invalid.QUESTION 4
What is the primary flaw in this loop?
while (iter1 < iter2) where iter is a list<int>::iterator?Lists only support
!= comparison for iterators.The loop will result in an infinite recursion.
List iterators must be decremented.
You cannot compare iterators of the same container.
✅ Correct!
Correct! Because lists are not stored contiguously, the < operator is not defined; use != instead.❌ Incorrect
The < operator is only defined for random-access iterators (like vector or deque).QUESTION 5
Why would you call
is.clear() before returning an istream& from a function?To delete all data within the stream.
To reset the error state (like EOF) so the caller can continue using it.
To flush the output buffer.
To close the associated file handle.
✅ Correct!
Once a stream hits EOF, it remains in an error state. clear() resets the state bits.❌ Incorrect
clear() affects the state flags, not the data contents or file connection.Case Study: The polymorphic Logging & Storage System
Managing Stream IO and Sequential Containers
You are designing a system that reads user input and stores it. You need a function that can read from either the standard console (cin) or a file, stores every word individually, and returns the stream to a healthy state for the next component.
Q
1. Implement Exercise 8.1: Write the C++ function that reads an istream until EOF, prints the content, and resets the stream.
Solution:
The function would look like this:
The function would look like this:
istream& readAndReset(istream &is) {
string val;
while (is >> val) {
cout << val << endl;
}
is.clear(); // Essential to reset EOF state
return is;
}Q
2. Provide a usage guide for when to select: vector, list, deque, map, and set.
Solution:
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
Q
3. Exercise 8.5: How would you modify a program to store each word of a file into a vector of strings?
Solution:
By using the extraction operator
By using the extraction operator
>>, which naturally stops at whitespace: string word;
while (inputFile >> word) {
vec.push_back(word);
} This differs from getline(), which reads whole lines including spaces.